package cn.whb.hrm.smslogin;

import cn.whb.hrm.service.MyUserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class SmsCodeProvider implements AuthenticationProvider {


    private UserDetailsService userDetailsService;
    public void setUserDetailsService(UserDetailsService userDetailsService){
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Object phone = authentication.getPrincipal();
        UserDetails user = userDetailsService.loadUserByUsername(phone.toString());
        if (user == null){
            throw new RuntimeException("该用户不存在");
        }
        PhoneCodeAuthenticationToken token = new PhoneCodeAuthenticationToken(authentication.getPrincipal(),authentication.getCredentials(),user.getAuthorities());
        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (PhoneCodeAuthenticationToken.class
                .isAssignableFrom(authentication));
    }

}
